package com.sscl.baselibrary.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.sscl.baselibrary.exts.getParameterizedType

/**
 * BaseMvvmForDataBindingFragment
 *
 * @author jackie Penghe
 * @date 2025/8/28
 */
abstract class BaseMvvmForDataBindingFragment<DB : ViewDataBinding, VM : ViewModel> :
    BaseDataBindingFragment<DB>() {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 属性声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /* * * * * * * * * * * * * * * * * * * 子类可用属性 * * * * * * * * * * * * * * * * * * */

    protected lateinit var mViewModel: VM

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initViewModel()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    /**
     * 初始化控件数据
     */
    override fun initViewData(savedInstanceState: Bundle?) {
        initViewModelObserve(savedInstanceState)
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 抽象方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 初始化ViewModel观察者
     */
    abstract fun initViewModelObserve(savedInstanceState: Bundle?)

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    private fun initViewModel() {
        val parameterizedType = getParameterizedType()
        val argument = parameterizedType.actualTypeArguments
        @Suppress("UNCHECKED_CAST")
        mViewModel = ViewModelProvider(this)[argument[1] as Class<VM>]
    }
}